package com.movie.service.impl;

import com.movie.model.Movie;
import com.movie.model.Screening;
import com.movie.service.MovieService;
import com.movie.util.DataUtil;
import java.util.List;
import java.util.stream.Collectors;

public class MovieServiceImpl implements MovieService {

  private DataUtil dataUtil;

  public MovieServiceImpl(DataUtil dataUtil) {
      this.dataUtil = dataUtil;
  }

    @Override
    public List<Movie> searchMovies(String keyword) {
        List<Movie> movies = dataUtil.loadMovies();
         if(keyword == null || keyword.isEmpty()){
            return movies;
        }
        String finalKeyword = keyword.toLowerCase();
       return movies.stream().filter(movie -> movie.getTitle().toLowerCase().contains(finalKeyword) ||
                movie.getDirector().toLowerCase().contains(finalKeyword) ||
              movie.getGenre().toLowerCase().contains(finalKeyword)).collect(Collectors.toList());
    }

    @Override
    public List<Screening> getScreeningsByMovie(String movieId) {
       List<Screening> screenings = dataUtil.loadScreenings();
       return screenings.stream().filter(screening -> screening.getMovieId().equals(movieId)).collect(Collectors.toList());
    }

    @Override
    public Screening getScreeningById(String id) {
     List<Screening> screenings = dataUtil.loadScreenings();
     return  screenings.stream().filter(screening -> screening.getId().equals(id)).findFirst().orElse(null);
    }

 @Override
 public void updateScreening(Screening screening) {
     List<Screening> screenings = dataUtil.loadScreenings();
     for (int i = 0; i < screenings.size(); i++) {
         if (screenings.get(i).getId().equals(screening.getId())) {
              screenings.set(i,screening);
              break;
           }
     }
     dataUtil.saveScreenings(screenings);
 }
}